package com.imooc.controller;

import java.util.List;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.dao.GirlRepository;
import com.imooc.pojo.Girl;
import com.imooc.pojo.Result;
import com.imooc.result.ResultUtil;
import com.imooc.service.GirlService;

/**
* @ClassName: GirlControlller 
* @Description: TODO 
* @author zyd
* @date 2017年12月8日 上午10:36:43
 */
@RestController
public class GirlControlller {

	private final static Logger logger = LoggerFactory.getLogger(GirlControlller.class);
	
	@Autowired
	private GirlRepository girlRepository;
	
	@Autowired
	private GirlService girlService;
	/**
	 * 获取女生列表
	 * @return
	 */
	@GetMapping(value="/girls")
	public List<Girl> girlList(){
		logger.info("girlList");
		return girlRepository.findAll();
	}
	
	/**
	 * 添加一个女生
	 * @param cupSize
	 * @param age
	 * @return
	 */
	@PostMapping(value="/girls")
	public Result<Girl> girlAdd(@Valid Girl girl,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
		}
		girl.setCupSize(girl.getCupSize());
		girl.setAge(girl.getAge());
		
		return ResultUtil.success(girlRepository.save(girl));
	}
	
	/**
	 * 查询一个女生
	 * @param id
	 * @return
	 */
	@GetMapping(value="/girls/{id}")
	public Girl findGirlById(@PathVariable("id") Integer id){
		return girlRepository.findOne(id);
	}
	
	/**
	 * 更新
	 * @param id
	 */
	@PostMapping(value="/girls/{id}")
	public Girl updateGirl(@PathVariable("id") Integer id,
			@RequestParam("cupSize") String cupSize,
			@RequestParam("age") Integer age){
		Girl girl = new Girl();
		girl.setCupSize(cupSize);
		girl.setAge(age);
		girl.setId(id);
		return  girlRepository.save(girl);
	} 
	
	/**
	 * 根据主键进行删除
	 * @param id
	 */
	@DeleteMapping(value="/girls/{id}")
	public void deleteGirlById(@PathVariable("id") Integer id){
		girlRepository.delete(id);
	}

	/**
	 * 根据年龄查询女生
	 * @param age
	 * @return
	 */
	@GetMapping(value="/girls/age/{age}")
	public List<Girl> girlListByAge(@RequestParam("age") Integer age){
		return girlRepository.findGrilsByAge(age);
	}
	
	/**
	 * 事务插入两条数据
	 */
	@PostMapping(value="/girls/two")
	public void girlTwo(){
		girlService.insertTwo();
	}
	
	@GetMapping(value="/girls/getAge/{id}")
	public void getAge(@PathVariable("id") Integer id) throws Exception{
		girlService.getAge(id);
	}
}
